package com.chinaunicom.auth.config;

import com.chinaunicom.auth.granter.SmsCodeTokenGranter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.CompositeTokenGranter;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author liry
 * @version 1.0
 * @date Created on 2021/3/5 15:53
 * Description: 配置token 存放在jwt， 配置第三方应用
 */

@Configuration
public class AuthorizationJWTConfig extends AuthorizationServerConfigurerAdapter {


    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;

    /**
     * jwt的token转换器， 把用户的信息转成jwt的形式颁发出去
     *
     * @return
     */
    @Bean
    public JwtAccessTokenConverter getJwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        // 非对称加密
        ClassPathResource classPathResource = new ClassPathResource("cxs-jwt.jks");
        // 创建钥匙工厂
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(classPathResource, "cxs123".toCharArray());

        // 通过别名获取私钥
        KeyPair keyPair = keyStoreKeyFactory.getKeyPair("cxs-jwt");

        converter.setKeyPair(keyPair);
        return converter;
    }

    /**
     * 让oauth的token 和 JWT存储进行关联
     */
    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(getJwtAccessTokenConverter());
    }


    /**
     * 配置第三方应用
     * 四种授权模式:
     * 1. code模式: authorization_code
     * 2. 静默授权:
     * 3. 密码模式: password
     * 4. 客户端授权
     *
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        super.configure(clients);
        clients.inMemory()
                .withClient("web")  // 第三方应用客户端名称
                .secret(passwordEncoder.encode("web-secret")) // 第三方应用密码
                .scopes("read") // 第三方应用作用域
                .authorizedGrantTypes("authorization_code") // code码授权
                .accessTokenValiditySeconds(7200) // token有效时间
                .redirectUris("https://www.baidu.com") // 授权后跳转的uri地址
                .and()
                // 配置第二个客户端信息:
                .withClient("qq")
                .secret(passwordEncoder.encode("qq-secret"))
                .scopes("write")
                .authorizedGrantTypes("password", "sms")  // 密码授权
                .accessTokenValiditySeconds(7200)
                .redirectUris("https://www.baidu.com");

    }


    /**
     * 需要暴露授权服务给token存储
     * 暴露授权服务器给认证管理器
     *
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        super.configure(endpoints);
        endpoints.accessTokenConverter(getJwtAccessTokenConverter())
                .authenticationManager(authenticationManager)
                .tokenGranter(tokenGranter(endpoints));
    }

    /**
     * 重点
     * 先获取已经有的五种授权，然后添加我们自己的进去
     *
     * @param endpoints AuthorizationServerEndpointsConfigurer
     * @return TokenGranter
     */
    private TokenGranter tokenGranter(final AuthorizationServerEndpointsConfigurer endpoints) {
        List<TokenGranter> granters = new ArrayList<>(Collections.singletonList(endpoints.getTokenGranter()));
        granters.add(new SmsCodeTokenGranter(authenticationManager, endpoints.getTokenServices(), endpoints.getClientDetailsService(),
                endpoints.getOAuth2RequestFactory()));
        return new CompositeTokenGranter(granters);
    }
}
